Access Specifiers in Java

Master scope and encapsulation rules across classes and packages

1. What are Access Specifiers?

Access Specifiers (also known as access modifiers) in Java define the scope and visibility of classes, constructors, variables, and methods. They control which other parts of your program can read or modify a specific member.

The 4 Access Levels in Java:
  • private: Accessible only within the declared class.
  • default (no modifier): Accessible within the same package.
  • protected: Accessible within the same package and by subclasses in other packages.
  • public: Accessible everywhere across all packages.
Public (Everywhere) Protected (Subclasses) & Default (Package) Private (Class Only)

2. Code Examples by Modifier

A. Private Modifier

Restricts access strictly inside the same class file.

package com.example;

public class Student {
    // Private variable cannot be accessed directly from outside
    private String secretCode = "1234";

    private void printSecret() {
        System.out.println(secretCode); // Allowed: Inside the same class
    }
}

B. Default Access (Package-Private)

Applied when no keyword is specified. Accessible to any class in the same package.

package com.example;

class Course { // Default class visibility
    String courseName = "Java Programming"; // Default variable visibility

    void display() { // Default method visibility
        System.out.println("Course: " + courseName);
    }
}

C. Protected Modifier

Accessible within the package and by child classes outside the package via inheritance.

package com.parent;

public class Person {
    protected String nationalId = "ID-9901";
}

// In a different package:
package com.child;
import com.parent.Person;

public class Employee extends Person {
    public void showId() {
        // Allowed because Employee inherits from Person
        System.out.println(nationalId); 
    }
}

D. Public Modifier

Provides unrestricted access from any package in the application.

package com.example;

public class Application {
    public String appName = "MyJavaApp";

    public void start() {
        System.out.println("App Started!");
    }
}

3. Access Specifiers Matrix

Use this reference table to quickly review access rules across different boundaries:

Access Modifier Same Class Same Package Subclass (Diff Package) World (Diff Package)
private Yes No No No
default (no modifier) Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes